import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import utils from 'src/common/utils';
import { Repository } from 'typeorm';
import { MultiImg } from '../multiImg/multiImg.entity';
import { UserSetting } from '../userSetting/userSetting.entity';
import { VideoEnum } from '../video/video.enum';
import { Concern } from './concern.entity';
import { UnConcern } from '../unconcern/unconcern.entity';
const friendVideoIdKey = 'friend_video_id'
import DataBase from 'src/config/database';

@Injectable()
export class ConcernService {
  constructor(
    @InjectRepository(Concern)
    private repository: Repository<Concern>,
    @InjectRepository(MultiImg)
    private multiImgRepository: Repository<MultiImg>,
    @InjectRepository(UserSetting)
    private userSettingRepository: Repository<UserSetting>,
    @InjectRepository(UnConcern)
    private unConcernRepository: Repository<UnConcern>,
  ) {}


  /**
   * 查询朋友圈是否有更新
   */
  async findIsUpdate(wx_user: string){
    let works = await this.repository.query(`
        select * from(
        -- 认证的网红
        select distinct video.id as video_id, video.create_time
        from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        inner join concern on concern.concern_ic_group = internet_celebrity_group.id
        where internet_celebrity_group.type = 2 and wx_user.openid in (
          select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
        ) and concern.wx_user = ? and video.check = 1 and video.profit_type = 1
        union
        -- tk的主页
        select distinct video.id as video_id, video.create_time
        from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join platform on platform.ic_group = internet_celebrity_group.id
        inner join concern on concern.concern_ic_group = internet_celebrity_group.id
        where (
            (internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3'))
            or internet_celebrity_group.type = 3
          )
          and concern.wx_user = ? and video.check = 1 and internet_celebrity_group.delete_tag = 0
          and (
            (
              (video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1)
              or (
                video.overseas = 0 and video.original = 1 and video.type = 0 and (video.in_ic = 1 or video.in_ic is null)
              )
              or (
                video.original = 0 and (video.in_ic = 1 or video.in_ic is null) and video.type = 0 
              )
              or (
                video.overseas = 1 and video.original = 1 and video.profit_type = 1
              )
            )
          )
        ) a
        order by a.create_time desc
        limit 0,1
    `,[wx_user, wx_user, wx_user])
    if(works.length > 0){
      let findLastVideoId:UserSetting = await this.userSettingRepository.findOne({where:{wx_user: wx_user,key: friendVideoIdKey}})
      if(findLastVideoId){
        console.log(findLastVideoId.value,works[0])
        if(Number(findLastVideoId.value) < Number(works[0].video_id)){
          return true
        }else{
          return false
        }
      }else{
        return true
      }
    }else{
      return false
    }
  }

  async findAll_Works(skip: number, take: number, wx_user: string): Promise<any[]> {
    let works = await this.repository.query(`
        select * from(
        -- 认证的网红
        select distinct video.id as video_id,video.video_cover, video.video_url, video.type, video.wx_user, video.create_time,
          'authen_work' as ic_type,
          internet_celebrity_group.id as wx_user_id, wx_user.name,wx_user.avatar_img,
          (select count(1) from profit p inner join answer ans on p.answer_id = ans.id where ans.video_id = video.id and ans.check = 1 and p.use_wx_user = ?) as is_profit
        from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        inner join concern on concern.concern_ic_group = internet_celebrity_group.id
        where internet_celebrity_group.type = 2 and wx_user.openid in (
          select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
        ) and concern.wx_user = ? and video.check = 1 and video.profit_type = 1
        union
        -- tk的主页
        select distinct video.id as video_id, video.video_cover, video.video_url, video.type, video.wx_user, video.create_time, 
          'otherNetwork_ic_info' as ic_type,
          internet_celebrity_group.id as wx_user_id, internet_celebrity_group.name,
          (select avatar_img from internet_celebrity ic where ic.ic_group = internet_celebrity_group.id order by ic.id asc limit 0,1) avatar_img,
          (select count(1) from profit p inner join answer ans on p.answer_id = ans.id where ans.video_id = video.id and ans.check = 1 and p.use_wx_user = ?) as is_profit
        from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join platform on platform.ic_group = internet_celebrity_group.id
        inner join concern on concern.concern_ic_group = internet_celebrity_group.id
        where (
            (internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3'))
            or internet_celebrity_group.type = 3
            or (video.overseas = 3 and internet_celebrity_group.type = 0 and video.original = 1)
          )
          and video.delete_tag = 0
          and concern.wx_user = ? and video.check = 1 and internet_celebrity_group.delete_tag = 0
          and (
            (
              (video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1)
              or (
                video.overseas = 0 and video.original = 1 and video.type = 0 and (video.in_ic = 1 or video.in_ic is null)
              )
              or (
                video.original = 0 and (video.in_ic = 1 or video.in_ic is null) and video.type = 0 
              )
              or (
                video.overseas = 1 and video.original = 1 and video.profit_type = 1
              )
            )
          )
        ) a
        order by a.create_time desc
        limit ?,?
    `,[wx_user, wx_user, wx_user, wx_user, skip, take])
   
    let maxVideoId = await this.repository.query(`
        select * from(
        -- 认证的网红
        select distinct video.id as video_id, video.create_time
        from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        inner join concern on concern.concern_ic_group = internet_celebrity_group.id
        where internet_celebrity_group.type = 2 and wx_user.openid in (
          select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
        ) and concern.wx_user = ? and video.check = 1 and video.profit_type = 1
        union
        -- tk的主页
        select distinct video.id as video_id, video.create_time
        from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join platform on platform.ic_group = internet_celebrity_group.id
        inner join concern on concern.concern_ic_group = internet_celebrity_group.id
        where (
            (internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3'))
            or internet_celebrity_group.type = 3
            or (video.overseas = 3 and internet_celebrity_group.type = 0 and video.original = 1)
          )
          and concern.wx_user = ? and video.check = 1 and internet_celebrity_group.delete_tag = 0 and video.delete_tag = 0
          and (
            (
              (video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1)
              or (
                video.overseas = 0 and video.original = 1 and video.type = 0 and (video.in_ic = 1 or video.in_ic is null)
              )
              or (
                video.original = 0 and (video.in_ic = 1 or video.in_ic is null) and video.type = 0 
              )
              or (
                video.overseas = 1 and video.original = 1 and video.profit_type = 1
              )
            )
          )
        ) a
        order by a.create_time desc
        limit 0,1
    `,[wx_user, wx_user, wx_user])

    if(maxVideoId.length > 0){
      let lastVideoId = maxVideoId[0].video_id
      let findLastVideoId:UserSetting = await this.userSettingRepository.findOne({where:{wx_user:wx_user,key: friendVideoIdKey}})
      let params = new UserSetting()
      params.wx_user = wx_user
      params.value = lastVideoId
      params.key = friendVideoIdKey
      let isUpdate = true
      if(findLastVideoId){
        params.id = findLastVideoId.id
        if(findLastVideoId.value == params.value){
          isUpdate = false
        }
      }
      if(isUpdate){
        await this.userSettingRepository.save(params)
      }
    }

    let multi_img_where = []
    let muliti_img_videos = works.filter(e => e.type == VideoEnum.image)
    muliti_img_videos.map(e => {
      multi_img_where.push({video_id:e.video_id})
    })
    let where:any = {
      order:{create_time:'ASC'}
    }
    if(multi_img_where.length > 0){
      where.where = multi_img_where
    }
    let multi_img = await this.multiImgRepository.find(where)

    muliti_img_videos.map(e => {
      e.multi_img = multi_img.filter(c => c.video_id == e.video_id)
      if(e.multi_img.length === 0){
        e.multi_img.push({
          video_id: e.video_id,
          img: e.video_cover
        })
      }
      if(e.wx_user == wx_user || e.is_profit > 0){
        e.multi_img.map(c => {
          c.is_profit_result = true
        })
      }
    })
    return works
  }

  findAll(): Promise<Concern[]> {
    return this.repository.find();
  }

  findOne(id: any): Promise<Concern> {
    return this.repository.findOne(id);
  }

  async remove(id: number, unconcern: string, wx_user: string): Promise<any> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      if(unconcern === 'unconcern'){
        await this.unConcernRepository.createQueryBuilder(null, queryRunner)
          .delete()
          .where({id: id})
          .execute()
      }else{
        await this.repository.createQueryBuilder(null, queryRunner)
          .delete()
          .where({id: id,wx_user: wx_user})
          .execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async create(concern: Concern): Promise<any> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let result = await this.repository.createQueryBuilder(null, queryRunner)
        .insert()
        .into(Concern)
        .values(concern)
        .execute()
      console.log(result,' result')
      // let findConcern = await this.repository.findOne({where:{concern_ic_group: concern.concern_ic_group, wx_user: concern.wx_user}})
      
      await queryRunner.commitTransaction()
      await queryRunner.release();

      if(result.generatedMaps[0]?.id){
        return {id:result.generatedMaps[0].id}
      }
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return {error: err}
    }
    
  }

  async findConcern_by_video_id(video_id: number, wx_user: string): Promise<Concern | Boolean> {
    //查找视频
    let video = await this.repository.query(`
      select concern.id as concern_ic_group_id
      from video
      left join concern on concern.concern_ic_group = video.ic_group
      where video.id = ? and concern.wx_user = ?
    `, [video_id, wx_user])
    if(video.length > 0){
      video = video[0]
      return video.concern_ic_group_id
    }else{
      return false
    }
  }

  async create_by_video_id(video_id: number, wx_user: string): Promise<Concern | Boolean> {
    //查找视频
    let video = await this.repository.query(`
      select video.ic_group, wx_user.id as wx_user_id, video.overseas, video.original
      from video
      inner join wx_user on wx_user.openid = video.wx_user
      where video.id = ?
    `, [video_id])
    let concern_ic_group = undefined,concern_wx_user_id = undefined
    if(video.length > 0){
      video = video[0]
      let concern = new Concern()

      if(video.overseas === 1 && video.original === 1){
        concern.concern_wx_user_id = video.wx_user_id
      }else{
        concern.concern_ic_group = video.ic_group
      }
      concern.create_time = new Date()
      concern.wx_user = wx_user
      return await this.create(concern)
    }else{
      return false
    }
  }

  _type(val){
    return Object.prototype.toString.call(val).slice(8,-1).toLowerCase()
  }

  _parseData(r) {
    // 生成a-z的数组
    let data = [];
    let chars = []
    for (let i = 65; i <= 90; i++) {
      let key = String.fromCharCode(i)
      data.push({"key":key,data:[]})
      chars.push(key)
    }
    let other = [35]
    other.map(i => {
      let key = String.fromCharCode(i)
      data.push({"key":key,data:[]})
      chars.push(key)
    })
    if(this._type(r) === "array") {
      
      // 填充数据
      r.forEach(o => {
        let isFind = false
        // 找到char的位置
        data.forEach( (item,index) => {
          let a = utils._parseChar(o['name'])
          if(item.key === a){
            data[index].data.push(o)
            isFind = true
          }
        })
        if(!isFind){
          data.find(c => c.key == '#').data.push(o)
        }
      })
    }
    // 组合最后数据并踢出没有匹配到a-z中的任意数据
    let finalData = []
    for (let i in data) {
      if(data[i].data.length > 0){
        finalData.push(data[i])
      }
    }

    return finalData
  }

  batchPlatform(platformList){
    platformList.map(e => {
      for(let key in e){
        if(e[key] === undefined || e[key] === null){
          e[key] = ''
        }
      }
    })
    platformList = platformList.filter(e => {
      return e.platform || e.account || e.avatar_img || e.ic_name || e.img
    })
    return platformList
  }

  async findAll_ByWx_User(wx_user: string, keyword?: string): Promise<Concern[]> {
    let local = await this.repository.query(`
      select wx_user.id as wx_user_id, wx_user.name, wx_user.avatar_img, concern.id as concern_id, wx_user.id_card,(
        select count(1) from video
        where video.wx_user = wx_user.openid and video.profit_type = 1 and video.original = 1
      ) as count_look_full_video
      from wx_user
      inner join internet_celebrity_group on internet_celebrity_group.wx_user = wx_user.openid 
      inner join concern on concern.concern_wx_user_id = wx_user.id
      where wx_user.openid in (
        select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
      ) and internet_celebrity_group.type = 2 and concern.wx_user = ?
        and (wx_user.name like ? or wx_user.id_card = ?)
    `,[wx_user,`%${keyword || ''}%`, utils.filteremoji(keyword || '')])
    
    local.filter(e => Number(e.count_look_full_video || 0) === 0).map(e => {
      e.name = e.name + '(暂停使用)'
    })

    //查询平台信息
    let platformList = await this.repository.query(`
      select platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
          'virtually_ic_info' as type
      from concern 
      inner join internet_celebrity on internet_celebrity.ic_group = concern.concern_ic_group
      inner join internet_celebrity_group on internet_celebrity_group.id = concern.concern_ic_group
      inner join platform on platform.ic_group = internet_celebrity_group.id
      where concern.concern_ic_group is not null and
        concern.wx_user = ?
        and (
          internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
          or internet_celebrity_group.type = 3
        )
      union
      select platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
        'local_ic_info' as type
      from wx_user a
      inner join internet_celebrity_group on internet_celebrity_group.wx_user = a.openid and internet_celebrity_group.type = 2
      inner join concern b on b.concern_wx_user_id = a.id
      left join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
      inner join platform on platform.ic_group = internet_celebrity_group.id
      where b.wx_user = ?
        and a.openid in (
          select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
        )
    `,[wx_user, wx_user])

    platformList = this.batchPlatform(platformList)

    local.map(e => {
      e.platformList = platformList.filter(c => c.type === 'local_ic_info' && c.id === e.id)
    })

    let unconcern = await this.unConcernRepository.query(`
      select b.id,a.name, a.id as unconcern_id from unconcern a
      inner join wx_user b on b.openid = a.concern_wx_user
      where a.wx_user = ? and a.name like ?
      union all
      select b.id,a.name, a.id as unconcern_id from unconcern a
      inner join internet_celebrity_group b on b.id = a.concern_ic_group
      where a.wx_user = ? and a.name like ?
    `,[wx_user, `%${keyword || ''}%`, wx_user, `%${keyword || ''}%`])

    unconcern.map(e => {
      e.name = e.name + '(已注销)'
      local.push(e)
    })

    let icGroups = await this.repository.query(`
      select distinct * from (
        select concern.concern_ic_group as id,concern.id as concern_id,internet_celebrity.avatar_img,internet_celebrity.name,internet_celebrity_group.id_card,(
          select count(1) from video as v
          inner join internet_celebrity_group as icg on icg.id = v.ic_group
          where v.ic_group = internet_celebrity_group.id and (
            (icg.type = 0 and v.ic_group in (select ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3'))
            or (
              (icg.type = 3 or icg.type = 2)
              and v.source != 2
            )
            or (
              icg.type = 0 and v.overseas = 3 and v.original = 1
            )
          )
          and icg.delete_tag = 0
          and 
            (
              -- 提问视频，进入网红主页
              (
                v.type = 0 and v.original = 0 and v.in_ic = 1
              )
              -- 非认证作品，进入网红主页
              or (
                v.overseas = 3 and v.profit_type = 1
              )
              -- 认证作品，看完整版
              or (
                v.overseas = 1 and v.profit_type = 1
              )
              -- 视频库视频
              or (
                v.overseas = 0 and v.type = 0 and (v.in_ic = 1 or v.in_ic is null)
              )
            )
        ) as count_look_full_video
        from concern 
        inner join internet_celebrity on internet_celebrity.ic_group = concern.concern_ic_group
        inner join internet_celebrity_group on internet_celebrity_group.id = concern.concern_ic_group
        inner join platform on platform.ic_group = internet_celebrity_group.id
        where concern.concern_ic_group is not null and
          concern.wx_user = ? and (internet_celebrity.name like ? or internet_celebrity_group.id_card = ? )
        order by internet_celebrity.id asc
      ) a
    `,[wx_user,`%${keyword || ''}%`, utils.filteremoji(keyword || '')])

    
    icGroups.map(e => {
      e.platformList = platformList.filter(c => c.type === 'virtually_ic_info' && c.id === e.id)
      if(Number(e.count_look_full_video || 0) === 0){
        e.name = e.name + '(暂停使用)'
      }
    })
    
    let idGroupDist:any = [...new Set(icGroups.map(e => e.id))]
    let dataGroup = []
    idGroupDist.map(e => {
      if(!dataGroup.find(c => c.id == e)){
        let findData = icGroups.find(c => c.id == e)
        dataGroup.push(findData)
        local.push(findData)
      }
    })

    if(keyword === undefined){
      // 找到char的位置
      local = this._parseData(local)
    }
    return local
  }
}
